package com.cn.qgx428.lazydiary.ui.activity.subActivity

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.cn.qgx428.lazydiary.Presenter.DiaryPresenter
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.Utils.FileUtil
import com.cn.qgx428.lazydiary.Utils.MConst
import com.cn.qgx428.lazydiary.Utils.PhotoChoseActivity
import com.cn.qgx428.lazydiary.Utils.SPUtil
import com.cn.qgx428.lazydiary.dialog.CustomAlertDialog
import com.cn.qgx428.lazydiary.dialog.LoadingDialog
import com.cn.qgx428.lazydiary.extension.getCurrenDayOfYear
import com.cn.qgx428.lazydiary.extension.getCurrenTimePrecise
import com.cn.qgx428.lazydiary.local.LAMessege
import com.cn.qgx428.lazydiary.local.LAction
import com.cn.qgx428.lazydiary.local.LActionWacher
import com.cn.qgx428.lazydiary.local.LManager
import com.cn.qgx428.lazydiary.network.Imageloader
import com.cn.qgx428.lazydiary.network.bean.Diary
import com.cn.qgx428.lazydiary.network.bean.DiaryContent
import com.cn.qgx428.lazydiary.ui.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_diary_edit.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.util.*

class DiaryEditActivity : BaseActivity(), LActionWacher {

    // 当前运作模式
    var runType = MConst.DIARY_CREATE
    /**
     * 供编辑模式下使用
     */
    val EDIT  = "编辑"
    var diary: Diary? = null
    var dContents: MutableList<DiaryContent> = mutableListOf()

    // 装载内容
    lateinit var paper: LinearLayout
    //  当前位置
    var position = 0
    lateinit var dialog: LoadingDialog

    override fun initUI() {
        hindActionBar()
        setStatuBarColor(Color.BLACK)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_diary_edit)
        runType = intent.extras.getString(MConst.DIARY_TYPE, MConst.DIARY_CREATE)
        paper = diaryEdit_paper
        LManager.newInstance().register(this, LAction.ACTION_GET_LOCAL_IMAGE)
        dialog = getLoadingDialog()
        initView()

        // 当前模式下，为在创建新的日记
        if (runType.equals(MConst.DIARY_CREATE)){
            createNewInputZone()
            diaryEdit_time.text = Calendar.getInstance().getCurrenDayOfYear()
        }
        // 当前模式下，是在编辑已有日志
        else{
            diary = intent.extras.getSerializable(MConst.DIARY_BUNDLE) as Diary
            diaryEdit_commit.setText(EDIT)
            diaryEdit_time.text = diary?.createtime
            diaryEdit_title.setText(diary?.title)
            diaryEdit_title.isEnabled = false
            getDiaryContent()
        }
    }

    private fun getDiaryContent() {
        DiaryPresenter.getDiaryContent(diary!!.id, {
            it.contents.forEach {
                if (it.type.equals(MConst.DIARY_TEXT_CONTENT)){
                    createNewInputZone(it.info)
                }else if (it.type.equals(MConst.DIARY_IMG_CONTENT)){
                    createImage(it.info)
                }
            }
        })
    }

    private fun initView() {
        diaryEdit_back.setOnClickListener { finish() }
        diaryEdit_commit.setOnClickListener {
            //如果是预览模式，不提交
            if (diaryEdit_commit.getText().equals(EDIT)){
                diaryEdit_commit.setText("保存")
                revokeAll()
            } else {
                commitDiary()
            }
        }
        diaryEdit_addImg.setOnClickListener{
            startActivity<PhotoChoseActivity>()
            overridePendingTransition(R.anim.from_center_appear_in, R.anim.keep)
        }
    }

    /**
     * 从预览模式进入编辑模式，唤醒控件
     */
    fun revokeAll(){
        for (i in 0..paper.childCount-1){
            val v = paper.getChildAt(i)
            if (v is EditText){
                v.isEnabled = true
            } else if (v is ImageView){
                //长按删除
                v.setOnLongClickListener {
                    val dialog = getCustomAlertDialog()
                    dialog.setMessage("确认删除吗")
                    dialog.setPos {
                    removeImage(it)
                    dialog.dismiss()
                    }
                dialog.show()
            true
                }
            }
        }
        diaryEdit_title.isEnabled = true
    }

    /**
     * 提交日记
     */
    fun commitDiary(){
//        Log.d("diary status: ", "开始哦")
        if (TextUtils.isEmpty(diaryEdit_title.text.toString())){
            toast("起个标题吧")
            return
        }
        dialog.show()
        val contents: MutableList<DiaryContent> = mutableListOf()
        for(i in 0..paper.childCount-1){
            var v = paper.getChildAt(i)
            if (v is EditText){
                val c = DiaryContent(MConst.DIARY_TEXT_CONTENT, v.text.toString(), i)
                contents.add(c)
                Log.d("diary status: " , v.text.toString())
            } else if(v is ImageView){
                val c = DiaryContent(MConst.DIARY_IMG_CONTENT, v.tag.toString(),i)
                contents.add(c)
                Log.d("diary status: ", v.tag.toString())
            }
        }
        // 创建
        if (runType == MConst.DIARY_CREATE){
            DiaryPresenter.createDiary(SPUtil.currntUserId().toInt(),
                    diaryEdit_title.text.toString(),
                    Calendar.getInstance().getCurrenTimePrecise(),
                    contents,
                    {
                        //                    toast("y!")
                        dialog.dismiss()
                        //通知更新
                        LManager.newInstance().trigger(LAction.ACTION_CREATE_DIARY)
                    })
        }
        // 更新
        else{
            DiaryPresenter.updateDiary(diary!!.id,
                    diaryEdit_title.text.toString(),
                    contents,
                    {
                        dialog.dismiss()
                        //通知更新
                        LManager.newInstance().trigger(LAction.ACTION_UPDATE_DIARY)
                        toast("已更新")
                        finish()
                    })
        }

    }

    /**
     *  创建新的editext
     */
    private fun createNewInputZone(txt: String = "") {
        val inputZone = EditText(this)
        val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        params.setMargins(0,10,0,10)
        inputZone.layoutParams = params
        inputZone.hint = "新的一行哦～"
        inputZone.background = null
        inputZone.textSize = 14f
        inputZone.setText(txt)
        inputZone.setHintTextColor(resources.getColor(R.color.Ivory))
        inputZone.setTextColor(resources.getColor(R.color.mDarkCyan))
        inputZone.setOnFocusChangeListener({
            v, hasFocus ->
            if (hasFocus){
                // 记住当前位置
                position = locate(v as EditText)
                Log.d("diary status: " , "locate edit: $position")
            }
        })
        if (runType == MConst.DIARY_EDIT){
            // 预览模式下不可聚焦
            inputZone.isEnabled = false
        }
        paper.addView(inputZone)
    }

    /**
     *  编辑时，创建新的ImageView时使用
     *  在当前位置插入ImageView
     */
    private fun insertImage(path: String){
        val img = ImageView(this)
        val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        params.setMargins(0,10,0,10)
        img.layoutParams = params
        img.setImageBitmap(BitmapFactory.decodeFile(path))
        // 让图片控件自己记住文件位置
        img.tag = path
        //长按删除
        img.setOnLongClickListener {
            val dialog = getCustomAlertDialog()
            dialog.setMessage("确认删除吗")
            dialog.setPos {
                removeImage(it)
                dialog.dismiss()
            }
            dialog.show()
            true
        }
        // 在当前位置后面加入此控件
        paper.addView(img,position+1)
        // 如果此图片处于最后位置，并且当前模式为创建模式, 创建新的输入区域
        val nowImgPosition = locate(img)
        Log.d("diary status: " , "img: $nowImgPosition  position: $position")
        if (nowImgPosition == paper.childCount-1 && runType.equals(MConst.DIARY_CREATE)){
            createNewInputZone()
        }
    }

    /**
     * 从编辑状态进入时，加载图片
     */
    private fun createImage(imgName: String){
        val img = ImageView(this)
        val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        params.setMargins(0,10,0,10)
        img.layoutParams = params
        // 让图片控件自己记住文件位置
       // img.tag = imgName
        //长按删除
//        img.setOnLongClickListener {
//            val dialog = getCustomAlertDialog()
//            dialog.setMessage("确认删除吗")
//            dialog.setPos {
//                removeImage(it)
//                dialog.dismiss()
//            }
//            dialog.show()
//            true
//        }
        paper.addView(img)
        Imageloader.download(this,img,imgName)
        img.tag = imgName
    }

    /**
     * 移除视图
     */
    private fun removeImage(v: View){
        paper.removeView(v)
    }

    private fun locate(v: View): Int{
        for (i in 0..paper.childCount-1){
            if (v == paper.getChildAt(i)){
                return i
            }
        }
        return  paper.childCount - 1
    }

    override fun onTrigger(action: String, msg: LAMessege) {
        if (action.equals(LAction.ACTION_GET_LOCAL_IMAGE)){
            insertImage(msg.arg1)
        }
    }

}
